package com.example.revise.ui.home

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.net.Uri
import android.util.Log
import android.view.GestureDetector
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import android.widget.TextView
import android.widget.VideoView
import androidx.core.view.GestureDetectorCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.revise.R
import com.example.revise.data.VideoItem

class VideoAdapter(private val videos: List<VideoItem>) : 
    RecyclerView.Adapter<VideoAdapter.VideoViewHolder>() {

    private var holders = mutableMapOf<Int, VideoViewHolder>()
    private val TAG = "VideoAdapter"

    inner class VideoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val videoView: VideoView = view.findViewById(R.id.videoView)
        val titleText: TextView = view.findViewById(R.id.titleText)
        val descriptionText: TextView = view.findViewById(R.id.descriptionText)
        val pauseIndicator: ImageView = view.findViewById(R.id.pauseIndicator)
        val favoriteHeart: ImageView = view.findViewById(R.id.favoriteHeart)
        var isPlaying = false
        var isPrepared = false

        private fun showFavoriteAnimation(isFavorite: Boolean) {
            // 重置动画状态
            favoriteHeart.alpha = if (isFavorite) 0f else 1f
            favoriteHeart.scaleX = if (isFavorite) 0.5f else 1f
            favoriteHeart.scaleY = if (isFavorite) 0.5f else 1f
            favoriteHeart.visibility = View.VISIBLE

            val animatorSet = AnimatorSet()
            animatorSet.interpolator = AccelerateDecelerateInterpolator()

            if (isFavorite) {
                // 收藏动画：从小到大，渐显然后消失
                val fadeIn = ObjectAnimator.ofFloat(favoriteHeart, "alpha", 0f, 1f)
                fadeIn.duration = 200

                val scaleX = ObjectAnimator.ofFloat(favoriteHeart, "scaleX", 0.5f, 1.2f)
                val scaleY = ObjectAnimator.ofFloat(favoriteHeart, "scaleY", 0.5f, 1.2f)
                scaleX.duration = 200
                scaleY.duration = 200

                val scaleDownX = ObjectAnimator.ofFloat(favoriteHeart, "scaleX", 1.2f, 1f)
                val scaleDownY = ObjectAnimator.ofFloat(favoriteHeart, "scaleY", 1.2f, 1f)
                scaleDownX.duration = 100
                scaleDownY.duration = 100
                scaleDownX.startDelay = 200
                scaleDownY.startDelay = 200

                val fadeOut = ObjectAnimator.ofFloat(favoriteHeart, "alpha", 1f, 0f)
                fadeOut.duration = 200
                fadeOut.startDelay = 600

                animatorSet.playTogether(fadeIn, scaleX, scaleY, scaleDownX, scaleDownY, fadeOut)
            } else {
                // 取消收藏动画：先显示，然后缩小渐隐
                val scaleX = ObjectAnimator.ofFloat(favoriteHeart, "scaleX", 1f, 0.5f)
                val scaleY = ObjectAnimator.ofFloat(favoriteHeart, "scaleY", 1f, 0.5f)
                val fadeOut = ObjectAnimator.ofFloat(favoriteHeart, "alpha", 0.5f, 0f)
                
                scaleX.duration = 500
                scaleY.duration = 500
                fadeOut.duration = 500

                animatorSet.playTogether(scaleX, scaleY, fadeOut)
            }

            animatorSet.start()
        }

        private val gestureDetector = GestureDetectorCompat(view.context, 
            object : GestureDetector.SimpleOnGestureListener() {
                override fun onDoubleTap(e: MotionEvent): Boolean {
                    val position = adapterPosition
                    if (position != RecyclerView.NO_POSITION) {
                        val video = videos[position]
                        video.isFavorite = !video.isFavorite
                        showFavoriteAnimation(video.isFavorite)
                    }
                    return true
                }

                override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                    if (isPrepared) {
                        if (isPlaying) {
                            pauseVideo(adapterPosition)
                        } else {
                            playVideo(adapterPosition)
                        }
                    }
                    return true
                }
            }
        )

        init {
            itemView.setOnTouchListener { v, event ->
                gestureDetector.onTouchEvent(event)
                true
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_video, parent, false)
        return VideoViewHolder(view)
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        try {
            val video = videos[position]
            holders[position] = holder
            
            // 设置视频
            val uri = Uri.parse("android.resource://${holder.itemView.context.packageName}/${video.videoResId}")
            holder.videoView.setVideoURI(uri)
            
            // 移除媒体控制器
            holder.videoView.setMediaController(null)
            
            // 设置标题和描述
            holder.titleText.text = video.title
            holder.descriptionText.text = video.description

            // 设置错误监听器
            holder.videoView.setOnErrorListener { mp, what, extra ->
                Log.e(TAG, "Video error: what=$what extra=$extra")
                holder.isPrepared = false
                true
            }
            
            // 自动播放视频
            holder.videoView.setOnPreparedListener { mediaPlayer ->
                Log.d(TAG, "Video prepared at position $position")
                mediaPlayer.isLooping = true
                holder.isPrepared = true
                if (position == 0) {
                    playVideo(position)
                }
            }

            // 设置初始状态
            holder.pauseIndicator.visibility = View.VISIBLE
            holder.isPlaying = false
            holder.isPrepared = false

        } catch (e: Exception) {
            Log.e(TAG, "Error in onBindViewHolder: ${e.message}")
            e.printStackTrace()
        }
    }

    fun playVideo(position: Int) {
        try {
            holders[position]?.let { holder ->
                if (holder.isPrepared && !holder.videoView.isPlaying) {
                    holder.videoView.start()
                    holder.isPlaying = true
                    holder.pauseIndicator.visibility = View.GONE
                    Log.d(TAG, "Playing video at position $position")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error playing video: ${e.message}")
            e.printStackTrace()
        }
    }

    fun pauseVideo(position: Int) {
        try {
            holders[position]?.let { holder ->
                if (holder.isPrepared && holder.videoView.isPlaying) {
                    holder.videoView.pause()
                    holder.isPlaying = false
                    holder.pauseIndicator.visibility = View.VISIBLE
                    Log.d(TAG, "Paused video at position $position")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error pausing video: ${e.message}")
            e.printStackTrace()
        }
    }

    override fun getItemCount() = videos.size
} 